using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;
using GomokuGame.AI;

namespace GomokuGame
{
    /// <summary>
    /// 游戏回放管理器
    /// </summary>
    public class GameReplayManager
    {
        /// <summary>
        /// 游戏记录
        /// </summary>
        public GameRecord GameRecord { get; private set; }
        
        /// <summary>
        /// 当前播放位置
        /// </summary>
        public int CurrentMoveIndex { get; private set; }
        
        /// <summary>
        /// 是否正在播放
        /// </summary>
        public bool IsPlaying { get; private set; }
        
        /// <summary>
        /// 播放速度（毫秒/步）
        /// </summary>
        public int PlaybackSpeed { get; set; }
        
        /// <summary>
        /// 游戏引擎引用
        /// </summary>
        private GameEngine gameEngine;
        
        /// <summary>
        /// 播放定时器
        /// </summary>
        private Timer playbackTimer;
        
        /// <summary>
        /// 回放事件
        /// </summary>
        public event EventHandler<ReplayEventArgs> ReplayEvent;
        
        public GameReplayManager(GameEngine engine)
        {
            gameEngine = engine;
            CurrentMoveIndex = -1;
            IsPlaying = false;
            PlaybackSpeed = 1000; // 默认1秒/步
            
            playbackTimer = new Timer();
            playbackTimer.Tick += PlaybackTimer_Tick;
        }
        
        /// <summary>
        /// 加载游戏记录
        /// </summary>
        public void LoadGameRecord(GameRecord record)
        {
            GameRecord = record;
            CurrentMoveIndex = -1;
            IsPlaying = false;
            playbackTimer.Stop();
            
            // 重置游戏引擎
            gameEngine.StartNewGame(record.GameInfo.GameMode, 
                record.GameInfo.AIDifficulty ?? AIDifficulty.Beginner,
                record.GameInfo.AIPlayer ?? PieceType.White);
            
            OnReplayEvent(ReplayEventType.Loaded, $"已加载对局：{record.GameInfo.BlackPlayer} vs {record.GameInfo.WhitePlayer}");
        }
        
        /// <summary>
        /// 开始播放
        /// </summary>
        public void StartPlayback()
        {
            if (GameRecord == null || CurrentMoveIndex >= GameRecord.Moves.Count - 1)
            {
                return;
            }
            
            IsPlaying = true;
            playbackTimer.Interval = PlaybackSpeed;
            playbackTimer.Start();
            
            OnReplayEvent(ReplayEventType.Playing, "开始播放");
        }
        
        /// <summary>
        /// 暂停播放
        /// </summary>
        public void PausePlayback()
        {
            IsPlaying = false;
            playbackTimer.Stop();
            
            OnReplayEvent(ReplayEventType.Paused, "暂停播放");
        }
        
        /// <summary>
        /// 停止播放
        /// </summary>
        public void StopPlayback()
        {
            IsPlaying = false;
            playbackTimer.Stop();
            CurrentMoveIndex = -1;
            
            // 重置游戏引擎
            if (GameRecord != null)
            {
                gameEngine.StartNewGame(GameRecord.GameInfo.GameMode,
                    GameRecord.GameInfo.AIDifficulty ?? AIDifficulty.Beginner,
                    GameRecord.GameInfo.AIPlayer ?? PieceType.White);
            }
            
            OnReplayEvent(ReplayEventType.Stopped, "停止播放");
        }
        
        /// <summary>
        /// 跳转到指定步数
        /// </summary>
        public void GoToMove(int moveIndex)
        {
            if (GameRecord == null || moveIndex < -1 || moveIndex >= GameRecord.Moves.Count)
            {
                return;
            }
            
            // 重置游戏引擎
            gameEngine.StartNewGame(GameRecord.GameInfo.GameMode,
                GameRecord.GameInfo.AIDifficulty ?? AIDifficulty.Beginner,
                GameRecord.GameInfo.AIPlayer ?? PieceType.White);
            
            // 重放到指定步数
            for (int i = 0; i <= moveIndex; i++)
            {
                var move = GameRecord.Moves[i];
                gameEngine.PlacePiece(move.Row, move.Col);
            }
            
            CurrentMoveIndex = moveIndex;
            OnReplayEvent(ReplayEventType.MoveChanged, $"跳转到第 {moveIndex + 1} 步");
        }
        
        /// <summary>
        /// 下一步
        /// </summary>
        public void NextMove()
        {
            if (GameRecord == null || CurrentMoveIndex >= GameRecord.Moves.Count - 1)
            {
                return;
            }
            
            CurrentMoveIndex++;
            var move = GameRecord.Moves[CurrentMoveIndex];
            gameEngine.PlacePiece(move.Row, move.Col);
            
            OnReplayEvent(ReplayEventType.MoveChanged, $"第 {CurrentMoveIndex + 1} 步");
        }
        
        /// <summary>
        /// 上一步
        /// </summary>
        public void PreviousMove()
        {
            if (GameRecord == null || CurrentMoveIndex <= -1)
            {
                return;
            }
            
            // 重置并重放到上一步
            GoToMove(CurrentMoveIndex - 1);
        }
        
        /// <summary>
        /// 快进（跳过多步）
        /// </summary>
        public void FastForward(int steps = 5)
        {
            int targetIndex = Math.Min(CurrentMoveIndex + steps, GameRecord.Moves.Count - 1);
            GoToMove(targetIndex);
        }
        
        /// <summary>
        /// 快退（回退多步）
        /// </summary>
        public void FastRewind(int steps = 5)
        {
            int targetIndex = Math.Max(CurrentMoveIndex - steps, -1);
            GoToMove(targetIndex);
        }
        
        /// <summary>
        /// 设置播放速度
        /// </summary>
        public void SetPlaybackSpeed(int milliseconds)
        {
            PlaybackSpeed = Math.Max(100, Math.Min(5000, milliseconds)); // 限制在100-5000ms之间
            if (IsPlaying)
            {
                playbackTimer.Interval = PlaybackSpeed;
            }
        }
        
        /// <summary>
        /// 获取播放进度百分比
        /// </summary>
        public double GetPlaybackProgress()
        {
            if (GameRecord == null || GameRecord.Moves.Count == 0)
            {
                return 0.0;
            }
            
            return (double)(CurrentMoveIndex + 1) / GameRecord.Moves.Count * 100.0;
        }
        
        /// <summary>
        /// 获取当前移动信息
        /// </summary>
        public MoveRecord GetCurrentMove()
        {
            if (GameRecord == null || CurrentMoveIndex < 0 || CurrentMoveIndex >= GameRecord.Moves.Count)
            {
                return null;
            }
            
            return GameRecord.Moves[CurrentMoveIndex];
        }
        
        /// <summary>
        /// 播放定时器事件
        /// </summary>
        private void PlaybackTimer_Tick(object sender, EventArgs e)
        {
            if (CurrentMoveIndex >= GameRecord.Moves.Count - 1)
            {
                // 播放完成
                PausePlayback();
                OnReplayEvent(ReplayEventType.Completed, "播放完成");
                return;
            }
            
            NextMove();
        }
        
        /// <summary>
        /// 触发回放事件
        /// </summary>
        private void OnReplayEvent(ReplayEventType eventType, string message)
        {
            ReplayEvent?.Invoke(this, new ReplayEventArgs
            {
                EventType = eventType,
                Message = message,
                CurrentMoveIndex = CurrentMoveIndex,
                TotalMoves = GameRecord?.Moves.Count ?? 0,
                Progress = GetPlaybackProgress()
            });
        }
        
        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            playbackTimer?.Dispose();
        }
    }
    
    /// <summary>
    /// 回放事件类型
    /// </summary>
    public enum ReplayEventType
    {
        Loaded,      // 加载完成
        Playing,     // 开始播放
        Paused,      // 暂停
        Stopped,     // 停止
        MoveChanged, // 移动改变
        Completed    // 播放完成
    }
    
    /// <summary>
    /// 回放事件参数
    /// </summary>
    public class ReplayEventArgs : EventArgs
    {
        public ReplayEventType EventType { get; set; }
        public string Message { get; set; }
        public int CurrentMoveIndex { get; set; }
        public int TotalMoves { get; set; }
        public double Progress { get; set; }
    }
} 